//
//  ImageViewController.m
//  GentlemanAnime
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "ImageViewController.h"
#import "ImageTableViewCell.h"
#import "HTTPTool.h"
#import "ImageTableViewModel.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "ImageDetailViewController.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "SearchViewController.h"
#import "FireView.h"


#import "DownloadSingletonTool.h"

#import "ShaiXuan.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ImageViewController () <UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)NSMutableArray *picArr;
@property(nonatomic, retain)NSMutableArray *fuliArr;
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, copy)NSString *nextDataID;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, retain)MBProgressHUD *hud;
// 小火箭
@property(nonatomic, retain)UIButton *topButton;
@property(nonatomic, retain)FireView *fire;

@end

@implementation ImageViewController

- (void)dealloc
{
    [_titlelebel release];
    [_hud release];
    [_fire release];
    [_HUD release];
    [_nextDataID release];
    [_scrollView release];
    [_imageTableView release];
    [_picArr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.picArr = [NSMutableArray array];
        self.fuliArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    self.titlelebel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    if ([DownloadSingleton shareDownloadSingleton].fuli) {
        self.titlelebel.text = @"特色麻吉";
    } else {
        self.titlelebel.text = @"漫图";
    }
    self.titlelebel.font = [UIFont boldSystemFontOfSize:18];
    self.titlelebel.textAlignment = NSTextAlignmentCenter;
    self.titlelebel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.titlelebel;
    [_titlelebel release];
    
//    // 建立左右两个button
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    rightButton.frame = CGRectMake(0, 0, 30, 30);
//    [rightButton setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
//    [rightButton addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightButton] autorelease];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton setImage:[UIImage imageNamed:@"用户1"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:leftButton] autorelease];
    
    // 建立一个tableView
    self.imageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    self.imageTableView.rowHeight = (HEIGHT - 113) / 3;
    self.imageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.imageTableView.dataSource = self;
    self.imageTableView.delegate = self;
    [self.view addSubview:self.imageTableView];
    [_imageTableView release];
 
    [self createData];
    
    // 小菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    self.HUD.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];
    
    // 下拉刷新,上拉加载
    [self.imageTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.imageTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 置顶按钮点击方法
- (void)topButtonClick:(UIButton *)button {
    CGRect oldRect = self.topButton.frame;
    [UIView animateWithDuration:0.6 animations:^{
        self.fire.alpha = 1;
    } completion:^(BOOL finished) {
        [self.imageTableView setContentOffset:CGPointMake(0, 0) animated:YES];
        [UIView animateWithDuration:0.7 animations:^{
            self.topButton.frame = CGRectMake(oldRect.origin.x, oldRect.origin.y - 200, oldRect.size.width, oldRect.size.height);
            self.topButton.alpha = 0;
            self.fire.alpha = 0;
        } completion:^(BOOL finished) {
            self.topButton.frame = oldRect;
            [UIView animateWithDuration:0.1 animations:^{
                self.topButton.alpha = 1;
            }];
        }];
    }];
}

#pragma mark 上拉加载方法
- (void)footerRereshing {
    if ([self.nextDataID integerValue] <= 1) {
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];
        self.hud.mode = MBProgressHUDModeText;
        self.hud.labelText = @"没有更多数据了";
        [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(HUDtimer) userInfo:nil repeats:NO];
        
    } else {
        NSString *URL = [NSString stringWithFormat:@"http://acg.18touch.com/api/special?ak=&dk=e566b36fd99f9576285804a58f3e4fe3d4883441&lastId=%@&v=1.2",self.nextDataID];
        [HTTPTool get:URL body:nil httpResultStyle:JSON success:^(id result) {
            NSDictionary *dic = result;
            NSArray *listArr = dic[@"data"];
            NSDictionary *lastDic = [listArr lastObject];
            self.nextDataID = lastDic[@"id"];
            for (NSDictionary *tempDic in listArr) {
                ImageTableViewModel *imageModel = [[ImageTableViewModel alloc] init];
                [imageModel setValuesForKeysWithDictionary:tempDic];
                if (!(FULIARR)) {
                    [self.picArr addObject:imageModel];
                } else {
                    [self.fuliArr addObject:imageModel];
                }
                [imageModel release];
            }
//            self.nextDataID = ((ImageTableViewModel *)[self.picArr lastObject]).Id;
            [self.imageTableView reloadData];
            [self.imageTableView footerEndRefreshing];
        } failure:^(NSError *error) {
            
        }];
        
    }
}

- (void)HUDtimer {
    [self.imageTableView footerEndRefreshing];
    [self.hud hide:YES];
    [self.hud removeFromSuperview];
}

#pragma mark 下拉刷新方法
- (void)headerRereshing {
    [HTTPTool get:@"http://acg.18touch.com/api/special?ak=&dk=e566b36fd99f9576285804a58f3e4fe3d4883441&v=1.2" body:nil httpResultStyle:JSON success:^(id result) {
        [self.picArr removeAllObjects];
        NSDictionary *dic = result;
        NSArray *listArr = dic[@"data"];
        NSDictionary *lastDic = [listArr lastObject];
        self.nextDataID = lastDic[@"id"];
        for (NSDictionary *tempDic in listArr) {
            ImageTableViewModel *imageModel = [[ImageTableViewModel alloc] init];
            [imageModel setValuesForKeysWithDictionary:tempDic];
            if (!(FULIARR)) {
                [self.picArr addObject:imageModel];
            } else {
                [self.fuliArr addObject:imageModel];
            }
            [imageModel release];
        }
        
        [self.imageTableView reloadData];
        [self.imageTableView headerEndRefreshing];
    } failure:^(NSError *error) {
        
        
    }];
}

// 解析数据
- (void)createData
{
    [HTTPTool get:@"http://acg.18touch.com/api/special?ak=&dk=e566b36fd99f9576285804a58f3e4fe3d4883441&v=1.2" body:nil httpResultStyle:JSON success:^(id result) {
        NSDictionary *dic = result;
        NSArray *listArr = dic[@"data"];
        NSDictionary *lastDic = [listArr lastObject];
        self.nextDataID = lastDic[@"id"];
        for (NSDictionary *tempDic in listArr) {
            ImageTableViewModel *imageModel = [[ImageTableViewModel alloc] init];
            [imageModel setValuesForKeysWithDictionary:tempDic];
            if (!(FULIARR)) {
                [self.picArr addObject:imageModel];
            } else {
                [self.fuliArr addObject:imageModel];
            }
            [imageModel release];
        }
        [self.imageTableView reloadData];
        [self createTopButton];
        [self.HUD hide:YES];
    } failure:^(NSError *error) {
        
        
    }];
}

- (void)createTopButton {
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 60, self.view.frame.size.height - 106, 40, 40)];
    backView.backgroundColor = [UIColor colorWithRed:0.230 green:0.692 blue:0.901 alpha:0.800];
    backView.layer.cornerRadius = 20;
    [self.view addSubview:backView];
    [backView release];
    
    UIView *midView = [[UIView alloc] initWithFrame:CGRectMake(1, 1, 38, 38)];
    midView.layer.cornerRadius = 18;
    midView.layer.borderWidth = 1.5f;
    midView.layer.borderColor = [[UIColor colorWithRed:0.965 green:0.980 blue:0.992 alpha:1.000] CGColor];
    [backView addSubview:midView];
    [midView release];
    
    // 置顶按钮
    self.topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.topButton.frame = CGRectMake(6, 6, 28, 28);
    [backView addSubview:self.topButton];
    [self.topButton setTintColor:[UIColor whiteColor]];
    [self.topButton setImage:[UIImage imageNamed:@"iconfont-top(2)"] forState:UIControlStateNormal];
    [self.topButton addTarget:self action:@selector(topButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.fire = [[FireView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
    self.fire.center = CGPointMake(14, 35);
    self.fire.alpha = 0;
    [self.topButton addSubview:self.fire];
    [_fire release];
    self.fire.transform = CGAffineTransformRotate(self.fire.transform, M_PI);
}

#define mark tableView的两个协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([DownloadSingleton shareDownloadSingleton].fuli) {
        return self.fuliArr.count;
    } else {
        return self.picArr.count;
    }

    return self.picArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    ImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[ImageTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ImageTableViewModel *imageModel = nil;
    if ([DownloadSingleton shareDownloadSingleton].fuli) {
        imageModel = self.fuliArr[indexPath.row];
    } else {
        imageModel = self.picArr[indexPath.row];
    }
  
    [cell.upImageView sd_setImageWithURL:[NSURL URLWithString:imageModel.coverImageURL] placeholderImage:[UIImage imageNamed:@"漫图占位图"]];

    cell.downLabel.text = imageModel.PicTitle;
    cell.countLabel.text = imageModel.imageCount;
    cell.likeLabel.text = imageModel.likeCount;
    return cell;
}

#pragma mark tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ImageTableViewModel *model = nil;
    if ([DownloadSingleton shareDownloadSingleton].fuli) {
        model = self.fuliArr[indexPath.row];
    } else {
        model = self.picArr[indexPath.row];
    }
    
    ImageDetailViewController *imageDetailVC = [[ImageDetailViewController alloc] init];
    imageDetailVC.Id = model.Id;
    imageDetailVC.modeltitle = model.PicTitle;
    imageDetailVC.imageModel = model;
    [self.navigationController pushViewController:imageDetailVC animated:YES];
    [imageDetailVC release];
}

#pragma mark 两个button的点击方法
- (void)leftClick:(UIButton *)button
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC openLeftView];
}

//- (void)rightClick:(UIButton *)button
//{
//    SearchViewController *searchVC = [[SearchViewController alloc] init];
//    [self.navigationController pushViewController:searchVC animated:YES];
//    [searchVC release];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
